import 'dart:math';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:lucky_orbs/data/models/lottery_ticket.dart';
import 'super_lotto_event.dart';
import 'super_lotto_state.dart';

class SuperLottoBloc extends Bloc<SuperLottoEvent, SuperLottoState> {
  SuperLottoBloc() : super(SuperLottoInitial()) {
    on<GenerateRandomTicket>(_onGenerateRandomTicket);
    on<StartDrawing>(_onStartDrawing);
    on<ResetDrawing>(_onResetDrawing);
  }

  void _onGenerateRandomTicket(GenerateRandomTicket event, Emitter<SuperLottoState> emit) {
    final frontNumbers = _generateUniqueRandoms(5, 35);
    final backNumbers = _generateUniqueRandoms(2, 12);
    final ticket = LotteryTicket(
      type: LotteryType.superLotto,
      frontAreaNumbers: frontNumbers,
      backAreaNumbers: backNumbers,
    );
    emit(SuperLottoTicketReady(ticket));
  }

  Future<void> _onStartDrawing(StartDrawing event, Emitter<SuperLottoState> emit) async {
    emit(SuperLottoDrawing());

    await Future.delayed(const Duration(seconds: 7)); // 模拟摇奖动画时间

    final winningFront = _generateUniqueRandoms(5, 35);
    final winningBack = _generateUniqueRandoms(2, 12);
    final result = LotteryResult(
      type: LotteryType.superLotto,
      drawnFrontNumbers: winningFront,
      drawnBackNumbers: winningBack,
    );

    final prize = _calculatePrize(event.userTicket, result);
    emit(SuperLottoFinished(userTicket: event.userTicket, result: result, prizeDescription: prize));
  }
  
  void _onResetDrawing(ResetDrawing event, Emitter<SuperLottoState> emit) {
    emit(SuperLottoInitial());
  }

  List<int> _generateUniqueRandoms(int count, int max) {
    final random = Random();
    final Set<int> numbers = {};
    while (numbers.length < count) {
      numbers.add(random.nextInt(max) + 1);
    }
    final numberList = numbers.toList();
    numberList.sort();
    return numberList;
  }

  String _calculatePrize(LotteryTicket userTicket, LotteryResult winningResult) {
    final frontMatches = userTicket.frontAreaNumbers.where((num) => winningResult.drawnFrontNumbers.contains(num)).length;
    final backMatches = userTicket.backAreaNumbers.where((num) => winningResult.drawnBackNumbers.contains(num)).length;

    if (frontMatches == 5 && backMatches == 2) {
      return "🎉 一等奖！恭喜您！🎉";
    } else if (frontMatches == 5 && backMatches == 1) {
      return "二等奖！";
    } else if (frontMatches == 5 && backMatches == 0) {
      return "三等奖！";
    } else if (frontMatches == 4 && backMatches == 2) {
      return "四等奖！";
    } else if (frontMatches == 4 && backMatches == 1) {
      return "五等奖！";
    } else if (frontMatches == 3 && backMatches == 2) {
      return "六等奖！";
    } else if (frontMatches == 4 && backMatches == 0) {
      return "七等奖！";
    } else if (frontMatches == 3 && backMatches == 1 || frontMatches == 2 && backMatches == 2) {
      return "八等奖！";
    } else if (frontMatches + backMatches >= 3) {
      return "九等奖！";
    } else {
      return "很遗憾，未中奖。";
    }
  }
}